<template>
  <div>
    <el-card class="box-card">
      <!-- 顶部添加按钮 -->
      <el-button
        icon="Plus"
        type="primary"
        size="default"
        @click="addTrademark"
      >
        添加品牌
      </el-button>
      <!-- 表格组件,用于展示已有的数据 -->
      <el-table :data="trademarkAr" style="width: 100%; margin: 10px 0" border>
        <el-table-column label="序号" width="80" align="center" type="index" />
        <el-table-column label="品牌名称" align="center">
          <template #default="{ row }">
            <h1 style="color: red">{{ row.tmName }}</h1>
          </template>
        </el-table-column>
        <el-table-column label="品牌LOGO">
          <template #default="{ row }">
            <img
              :src="row.logoUrl"
              alt=""
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #default="{ row }">
            <el-button
              icon="Edit"
              type="primary"
              size="small"
              @click="updateTrademark(row)"
            ></el-button>

            <!-- 删除的气泡确认框 -->
            <el-popconfirm
              :title="`确认要删除${row.tmName}?`"
              width="250px"
              icon="Delete"
              icon-color="red"
              @confirm="removeTrademark(row.id)"
            >
              <template #reference>
                <el-button icon="Delete" type="danger" size="small"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件 -->
      <el-pagination
        @size-change="onSizeChange"
        @current-change="getHasTrademark"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 10]"
        :background="true"
        layout=" prev, pager, next, jumper,->,sizes,total"
        :total="total"
      />
    </el-card>
    <!-- 添加|修改按钮点击弹出的对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
    >
      <el-form :model="trademarkParams" :rules="rules" ref="formRef">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input
            placeholder="请输入品牌名称"
            v-model="trademarkParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">
          取消
        </el-button>
        <el-button type="primary" size="default" @click="confirm">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqAddOrUpdateTrademark,
  reqHasTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark/index'
import type {
  Records,
  TradeMark,
  TradeMarkResponseData,
} from '@/api/product/trademark/type'
import { ElMessage, UploadProps } from 'element-plus'
// 当前页码
const pageNo = ref<number>(1)
// 每一页展示的数据
const limit = ref<number>(10)
// 总数据条数
const total = ref<number>(100)
// 存储已有品牌的数据
const trademarkAr = ref<Records>([])
// 对话框的显示隐藏控制
const dialogVisible = ref<boolean>(false)
// 表单组件对象
const formRef = ref()

// 定义收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})
// 获取已有品牌的接口封装为一个函数
const getHasTrademark = async (pager = 1) => {
  // 当页码变化的时候调用此方法会注入对应的页数
  // 当每页数据量发生变化的时候不传值,从第一页开始
  pageNo.value = pager
  let result: TradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    limit.value,
  )
  if (result.code == 200) {
    // 存储已有品牌总个数
    total.value = result.data.total
    trademarkAr.value = result.data.records
  }
}
onMounted(() => {
  getHasTrademark()
})
// 当页面显示数据量变化时
const onSizeChange = () => {
  getHasTrademark()
}
// 添加品牌
const addTrademark = () => {
  dialogVisible.value = true
  // 每次弹出前,清空收集的数据
  trademarkParams.id = 0
  trademarkParams.logoUrl = ''
  trademarkParams.tmName = ''
  // 每次打开弹窗前,清除之前留下的规则校验信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
// 修改品牌
const updateTrademark = (row: TradeMark) => {
  dialogVisible.value = true
  // ES6语法合并对象
  Object.assign(trademarkParams, row)
  // 每次打开弹窗前,清除之前留下的规则校验信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
// 删除品牌
const removeTrademark = async (id: number) => {
  let result: any = reqDeleteTrademark(id)
  if (result.code == 200) {
    ElMessage.success('删除品牌成功')
    // 再次获取已有品牌数据
    getHasTrademark(
      trademarkAr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  } else {
    ElMessage.error('删除品牌失败')
  }
}
// 弹窗取消按钮
const cancel = () => {
  dialogVisible.value = false
}
// 弹窗确定按钮
const confirm = async () => {
  // 先校验规则
  await formRef.value.validate()

  // 调用方法添加品牌的接口数据上传
  let result: any = await reqAddOrUpdateTrademark(trademarkParams)
  // 如果添加|修改该成功
  if (result.code == 200) {
    dialogVisible.value = false
    // 弹出提示消息
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    // 再次发送请求获取已有的全部品牌数据,修改的时候要获取当前页面
    getHasTrademark(trademarkParams.id ? pageNo.value : 1)
  } else {
    ElMessage.error(trademarkParams.id ? '修改品牌失败' : '添加品牌失败')
    dialogVisible.value = false
  }
}
// 弹窗中上传图片前的回调方法
const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
  if (
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/gif' &&
    rawFile.type !== 'image/png'
  ) {
    ElMessage.error('上传的图片必须是JPEG}GIF|PNG格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('上传的图片大小不能超过4M!')
    return false
  }
  return true
}
// 弹窗中上传图片成功的回调方法
const handleAvatarSuccess: UploadProps['onSuccess'] = response => {
  // 收集图片的网络地址
  trademarkParams.logoUrl = response.data
  // 图片上传成功,清除掉对应图片校验结果
  formRef.value.clearValidate('logoUrl')
}
// 品牌自定义校验规则方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
  // 当表单元素 blur的时候触发
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('品牌名称位数大于等于两位'))
  }
}
// 品牌LOGO图片的自定义校验规则方法
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  // 当表单元素 blur的时候触发
  if (value) {
    callBack()
  } else {
    callBack(new Error('LOGO图片务必上传'))
  }
}

// 表单校验规则对象
const rules = {
  tmName: [{ required: true, trigger: 'blur', validator: validatorTmName }],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
}
</script>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
